package util;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author Kevin
 * @date 2020-12-29 19:27
 */
public class DatasourceUtil {

    private static final DruidDataSource DATASOURCE;

    private DatasourceUtil() {
    }

    static {
        try (InputStream resourceAsStream = Thread.currentThread()
                .getContextClassLoader().getResourceAsStream("database.properties")) {
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            DATASOURCE = new DruidDataSource();
            DATASOURCE.setUrl(properties.getProperty("url"));
            DATASOURCE.setUsername(properties.getProperty("user"));
            DATASOURCE.setPassword(properties.getProperty("password"));
        } catch (IOException e) {
            throw new IllegalAccessError("读取数据库配置失败！");
        }
    }

    public static Connection getConnection() throws SQLException {
        return DATASOURCE.getConnection();
    }

    public static ResultSet executeQuery(Connection connection,String sql,Object[] params) throws SQLException {
        System.out.println(" SQL 查询语句： \n " + sql);
        System.out.println(" 变量名： \n " + Arrays.asList(params) );
        PreparedStatement pstm = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pstm.setObject(i+1,params[i]);
        }
        return pstm.executeQuery();
    }


}
